package com.tbit.main.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import com.tbit.common.constant.OperationPlatform;
import com.tbit.common.entity.MachineOpLog;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.dao.log.UpKeepLogDao;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.UpKeepLog;
import com.tbit.main.pojo.UpKeepTypeLog;
import com.tbit.main.pojo.VO.UpKeepLogQueryReqVO;
import com.tbit.main.pojo.VO.UpKeepLogReqVO;
import com.tbit.main.pojo.VO.UpKeepLogRespVO;
import com.tbit.main.service.AccountUserService;
import com.tbit.main.service.RoleService;
import com.tbit.main.service.UpKeepLogService;
import com.tbit.main.service.UpKeepTypeLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author yao
 * @since 2025/1/23 10:05
 */
@Service
public class UpKeepLogServiceImpl implements UpKeepLogService {

    @Resource
    private UpKeepLogDao upKeepLogDao;

    @Resource
    private AccountUserService accountUserService;

    @Resource
    private UpKeepTypeLogService upKeepTypeLogService;

    @Resource
    private MachineOpLogService machineOpLogService;

    @Resource
    private RoleService roleService;

    @Override
    public List<UpKeepLogRespVO> getList(UpKeepLogQueryReqVO reqVO) {
        List<UpKeepLogRespVO> upKeepLogs = upKeepLogDao.selectList(reqVO);

        List<Integer> upKeepLogIds = upKeepLogs.stream().map(UpKeepLogRespVO::getId).collect(Collectors.toList());
        Map<Integer, List<UpKeepTypeLog>> upKeepTypeLogMap = upKeepTypeLogService.getByUpKeepLogIds(upKeepLogIds);

        upKeepLogs.forEach(upKeepLog -> {
            List<UpKeepTypeLog> upKeepTypeLogs = upKeepTypeLogMap.getOrDefault(upKeepLog.getId(), Collections.emptyList());
            String upKeepTypes = joinUpKeepType(upKeepTypeLogs);
            upKeepLog.setUpKeepTypes(upKeepTypes);
        });

        return upKeepLogs;
    }

    @Override
    public List<UpKeepLogRespVO> getCountList(UpKeepLogQueryReqVO reqVO) {
        AccountUser loginUser = LoginUserContextHolder.getLoginUser();

        // 管理员查看所有
        if (!roleService.getRoleCode(loginUser.getAccountUserType()).equals(1)) {
            reqVO.setAccountUserId(null);
        }

        List<UpKeepLogRespVO> upKeepLogs = upKeepLogDao.selectCountList(reqVO);
        List<Integer> accountUserIds = upKeepLogs.stream().map(UpKeepLogRespVO::getCreator).map(Integer::valueOf).collect(Collectors.toList());
        Map<Integer, AccountUser> accountUsers = accountUserService.getByIds(accountUserIds)
                .stream()
                .collect(Collectors.toMap(AccountUser::getAccountUserId, Function.identity()));
        upKeepLogs.forEach(upKeepLog -> {
            AccountUser accountUser = accountUsers.getOrDefault(Integer.valueOf(upKeepLog.getCreator()), new AccountUser());
            upKeepLog.setDelFlag(accountUser.getDelFlag());
        });
        return upKeepLogs;
    }

    @Override
    public UpKeepLogRespVO getById(Integer id) {
        UpKeepLog upKeepLog = upKeepLogDao.selectById(id);
        if (upKeepLog == null) {
            return null;
        }
        List<UpKeepTypeLog> upKeepTypeLogs = upKeepTypeLogService.getByUpKeepLogId(upKeepLog.getId());
        String upKeepTypes = joinUpKeepType(upKeepTypeLogs);
        UpKeepLogRespVO resp = BeanUtil.toBean(upKeepLog, UpKeepLogRespVO.class);
        resp.setUpKeepTypes(upKeepTypes);
        return resp;
    }

    @Override
    public void update(UpKeepLogReqVO reqVO) {

        UpKeepLog upKeepLog = upKeepLogDao.selectById(reqVO.getId());
        if (upKeepLog == null) {
            return;
        }

        UpKeepLog upKeepLogCopy = BeanUtil.toBean(reqVO, UpKeepLog.class);

        AccountUser loginUser = LoginUserContextHolder.getLoginUser();

        // 插入车辆操作日志
        machineOpLogService.insertSingle(MachineOpLog.builder()
                .accountId(upKeepLog.getAccountId())
                .machineId(upKeepLog.getMachineId())
                .machineNO(upKeepLog.getMachineNo())
                .userCode(upKeepLog.getUserCode())
                .opType(String.format("变更状态[%d->%d]", upKeepLog.getStatus(), reqVO.getStatus()))
                .operation("保养")
                .opUser(loginUser.getName())
                .opUserPhone(loginUser.getPhone())
                .opPlatform(OperationPlatform.MAINTAIN.code)
                .result(true)
                .opTime(LocalDateTime.now())
                .build()
        );

        upKeepLogCopy.setUpdater(loginUser.getAccountUserId().toString());
        upKeepLogCopy.setUpdateTime(new Date());

        upKeepLogDao.updateById(upKeepLogCopy);
    }

    @Override
    public void saveBatch(List<UpKeepLog> upKeepLogs) {
        if (CollUtil.isEmpty(upKeepLogs)) {
            return;
        }
        upKeepLogDao.insertBatch(upKeepLogs);
    }

    @Override
    public UpKeepLogRespVO getLastUpKeepLog(String userCode) {
        UpKeepLogRespVO upKeepLog = upKeepLogDao.selectLastUpkeepLog(userCode);
        if (upKeepLog == null) {
            return null;
        }
        List<UpKeepTypeLog> upKeepTypeLogs = upKeepTypeLogService.getByUpKeepLogId(upKeepLog.getId());
        String upKeepTypes = joinUpKeepType(upKeepTypeLogs);
        upKeepLog.setUpKeepTypes(upKeepTypes);
        return upKeepLog;
    }

    private String joinUpKeepType(List<UpKeepTypeLog> upKeepTypeLogs) {
        return upKeepTypeLogs.stream().map(UpKeepTypeLog::getUpKeepType).map(String::valueOf).collect(Collectors.joining(StrPool.COMMA));
    }
}
